﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;
namespace BYManageInfoSystem
{
    public partial class Frm_YewuRegTiSheet : DockContent
    {
        //private DGBY.BLL.PaidanRegisterDetailTab m_bllPaidanRegisterDetailTab = new DGBY.BLL.PaidanRegisterDetailTab();
        private DGBY.BLL.HxdNoTab m_bllHxdNoTab = new DGBY.BLL.HxdNoTab();
        private DGBY.BLL.PaidanRegisterTab m_bllPaidanRegisterTab = new DGBY.BLL.PaidanRegisterTab();

        private int m_nDelIndex = -1;
        public Frm_YewuRegTiSheet()
        {
            InitializeComponent();
        }
        public static void ultraGrid1_InitializeRowFilter(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.PerformAutoResize();
            // FILTER ROW FUNCTIONALITY RELATED ULTRAGRID SETTINGS
            //e.Layout.Override.RowFilterAction = RowFilterAction.DisableFilteredOutRows;
            // ----------------------------------------------------------------------------------
            // Enable the the filter row user interface by setting the FilterUIType to FilterRow.
            e.Layout.Override.FilterUIType = FilterUIType.FilterRow;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // FilterEvaluationTrigger specifies when UltraGrid applies the filter criteria typed 
            // into a filter row. Default is OnCellValueChange which will cause the UltraGrid to
            // re-filter the data as soon as the user modifies the value of a filter cell.
            e.Layout.Override.FilterEvaluationTrigger = FilterEvaluationTrigger.OnCellValueChange;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // By default the UltraGrid selects the type of the filter operand editor based on
            // the column's DataType. For DateTime and boolean columns it uses the column's editors.
            // For other column types it uses the Combo. You can explicitly specify the operand
            // editor style by setting the FilterOperandStyle on the override or the individual
            // columns.

            e.Layout.Override.FilterOperandStyle = FilterOperandStyle.DropDownList;

            // By default UltraGrid displays user interface for selecting the filter operator. 
            // You can set the FilterOperatorLocation to hide this user interface. This
            // property is available on column as well so it can be controlled on a per column
            // basis. Default is WithOperand. This property is exposed off the column as well.
            e.Layout.Override.FilterOperatorLocation = FilterOperatorLocation.WithOperand;

            // By default the UltraGrid uses StartsWith as the filter operator. You use
            // the FilterOperatorDefaultValue property to specify a different filter operator
            // to use. This is the default or the initial filter operator value of the cells
            // in filter row. If filter operator user interface is enabled (FilterOperatorLocation
            // is not set to None) then that ui will be initialized to the value of this
            // property. The user can then change the operator as he/she chooses via the operator
            // drop down.
            e.Layout.Override.FilterOperatorDefaultValue = FilterOperatorDefaultValue.StartsWith;

            // FilterOperatorDropDownItems property can be used to control the options provided
            // to the user for selecting the filter operator. By default UltraGrid bases 
            // what operator options to provide on the column's data type. This property is
            // avaibale on the column as well.
            //e.Layout.Override.FilterOperatorDropDownItems = FilterOperatorDropDownItems.All;

            // By default UltraGrid displays a clear button in each cell of the filter row
            // as well as in the row selector of the filter row. When the user clicks this
            // button the associated filter criteria is cleared. You can use the 
            // FilterClearButtonLocation property to control if and where the filter clear
            // buttons are displayed.
            e.Layout.Override.FilterClearButtonLocation = FilterClearButtonLocation.RowAndCell;

            // Appearance of the filter row can be controlled using the FilterRowAppearance proeprty.
            e.Layout.Override.FilterRowAppearance.BackColor = Color.LightYellow;

            // You can use the FilterRowPrompt to display a prompt in the filter row. By default
            // UltraGrid does not display any prompt in the filter row.
            e.Layout.Override.FilterRowPrompt = "Click here to filter data...";

            // You can use the FilterRowPromptAppearance to change the appearance of the prompt.
            // By default the prompt is transparent and uses the same fore color as the filter row.
            // You can make it non-transparent by setting the appearance' BackColorAlpha property 
            // or by setting the BackColor to a desired value.
            e.Layout.Override.FilterRowPromptAppearance.BackColorAlpha = Alpha.Opaque;

            // By default the prompt is spread across multiple cells if it's bigger than the
            // first cell. You can confine the prompt to a particular cell by setting the
            // SpecialRowPromptField property off the band to the key of a column.
            //e.Layout.Bands[0].SpecialRowPromptField = e.Layout.Bands[0].Columns[0].Key;

            // Display a separator between the filter row other rows. SpecialRowSeparator property 
            // can be used to display separators between various 'special' rows, including for the
            // filter row. This property is a flagged enum property so it can take multiple values.
            e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.FilterRow;

            // You can control the appearance of the separator using the SpecialRowSeparatorAppearance
            // property.
            e.Layout.Override.SpecialRowSeparatorAppearance.BackColor = Color.FromArgb(233, 242, 199);

            //   UltraGridBand band = e.Layout.Bands[0];
            //   band.ColumnFilters["原币金额"].FilterConditions.Clear();
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.GreaterThan, 5);
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.LessThan, 10);
            //   band.ColumnFilters["原币金额"].LogicalOperator = FilterLogicalOperator.And;
        }
        private void buttonShowAll_Click(object sender, EventArgs e)
        {
            ShowAllRecord(@"year(CASE WHEN year(ComebackGeneralSheet.申报日期) = 1900 or ComebackGeneralSheet.申报日期 is null then ComebackGeneralSheet.统计日期 else ComebackGeneralSheet.申报日期 end) = 2012
and (year(ComebackGeneralSheet.回收提单登记日期) = 1900 or ComebackGeneralSheet.回收提单登记日期 is null) 
and (datediff(month, CASE WHEN year(ComebackGeneralSheet.申报日期) = 1900 or ComebackGeneralSheet.申报日期 is null then ComebackGeneralSheet.统计日期 else ComebackGeneralSheet.申报日期 end, getdate()) > 2)");
        }
//        {
//            ShowAllRecord(@"year(CASE WHEN year(ComebackGeneralSheet.申报日期) > 1900 then ComebackGeneralSheet.申报日期 else ComebackGeneralSheet. 统计日期 end) = 2012
//and year(ComebackGeneralSheet.回收提单登记日期) = 1900 and (dateadd(day, -day(CASE WHEN year(ComebackGeneralSheet.申报日期) > 1900 then ComebackGeneralSheet.申报日期 else ComebackGeneralSheet. 统计日期 end)+1+60,CASE WHEN year(ComebackGeneralSheet.申报日期) > 1900 then ComebackGeneralSheet.申报日期 else ComebackGeneralSheet. 统计日期 end)) < getdate()");
//        }
        private void ShowAllRecord(string strWhere)
        {
            DataSet ds = m_bllHxdNoTab.ShowYewuRegTiSheetRec(strWhere);
            ultraGrid1.DataSource = null;

            ultraGrid1.DataSource = ds.Tables[0];
            //ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;

        }
        private void Frm_YewuRegTiSheet_Load(object sender, EventArgs e)
        {
            ClassUltraGridCommonSet.InitUltraWinGridSetting(this.ultraGrid1);
        }
        
        private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            if (this.checkBox1.Checked == true)
                ultraGrid1_InitializeRowFilter(e);
            else
                ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);
        
            ClassUltraGridCommonSet.InitUltraWinGridRowNumSetting(e);
            //ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);
            //ClassUltraGridCommonSet.LocalPrintPreveiw();
            foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
            {
                string str = column2.Header.Caption;
                if (str == "工厂名称" || str == "合同编号" || str == "申报日期" || str == "申报月份" || str == "集装箱柜号"
                    || str == "报关单号" || str == "核销单号" || str == "业务员"||str == "部门")
                {
                    column2.CellAppearance.BackColor = Color.FromArgb(255, 255, 128);
                    column2.CellActivation = Activation.ActivateOnly;
                }
            }
        }

        private void ultraGrid1_KeyDown(object sender, KeyEventArgs e)
        {
           
            switch (e.KeyCode)
            {

                case Keys.Up:
                    {
                        UltraGridCell gridCell = this.ultraGrid1.ActiveCell;
                        if (null == gridCell)
                            return;     

                        string strTemp = this.ultraGrid1.ActiveCell.Column.Header.Caption;
                        //if (strTemp == "经营公司" | strTemp == "客户" | strTemp == "币种" | strTemp == "收款方式")
                        //    return;
                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex > 0)
                            nIndex--;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.AboveCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Down:
                    {
                        UltraGridCell gridCell = this.ultraGrid1.ActiveCell;
                        if (null == gridCell)
                            return;     

                        string strTemp = this.ultraGrid1.ActiveCell.Column.Header.Caption;
                        //if (strTemp == "经营公司" | strTemp == "客户" | strTemp == "币种" | strTemp == "收款方式")
                        //    return;
                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex < ultraGrid1.Rows.Count - 1)
                            nIndex++;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.BelowCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Right:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.NextCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
                case Keys.Left:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.PrevCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
            }
        }

        private bool ModifyGoodsDetail(int nRowIndex)
        {

            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];
                string strContract = CurrentUGR.Cells["合同编号"].Value.ToString();
                DataSet ds = m_bllPaidanRegisterTab.GetList("ContractCode = '" + strContract + "'");
                int nPaidanRegisterTabID = (int)ds.Tables[0].Rows[0]["PaidanRegisterTabID"];
                ds = m_bllHxdNoTab.GetList("PaidanRegisterTabID = '" + nPaidanRegisterTabID.ToString() + "'");
                int nHxdNoTabID = (int)ds.Tables[0].Rows[0]["HxdNoTabID"];
                DGBY.Model.HxdNoTab modelHxdNoTab
                    = m_bllHxdNoTab.GetModel(nHxdNoTabID);

                modelHxdNoTab.HstddjDate = (DateTime)CurrentUGR.Cells["回收提单登记日期"].Value;
                modelHxdNoTab.HsbdzldjDate = (DateTime)CurrentUGR.Cells["回收放行条登记日期"].Value;
                modelHxdNoTab.Note = CurrentUGR.Cells["备注"].Value.ToString();
                
                m_bllHxdNoTab.Update(modelHxdNoTab);
                Frm_Main.Log2DB(this.Text, "修改", strContract);
                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ultraGrid1_BeforeRowUpdate(object sender, CancelableRowEventArgs e)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[e.Row.Index];

                ModifyGoodsDetail(e.Row.Index);


            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            int iIndex = this.ultraGrid1.ActiveCell.Row.Index;
            if (iIndex < 0)
                return;
            m_nDelIndex = ultraGrid1.ActiveRow.Index;
        }

        private void buttonExportExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
            Worksheet ws = e.CurrentWorksheet;
            int iRdex = e.CurrentRowIndex;
            int iCdex = e.CurrentColumnIndex;
            //e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].CellFormat.FillPatternForegroundColor = Color.FromArgb(0, 0, 0); 
            // string strColumnName = e.GridColumn;
            if (e.GridColumn.Key == "起始的核销单号" || e.GridColumn.Key == "终止的核销单号")
            {
                //m_ugr[iRdex-1].Cells[e.GridColumn.Key + "公式"].Value.ToString()
                string strNo = e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].Value.ToString();
                int nNo = Convert.ToInt32(strNo, 10);
                if (nNo < 100000000)
                    e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].Value = "0" + e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].Value;
            }
        }

    }
}
